<template>
  <CustomerLayout>
    <div class="orders-container">
      <!-- 页面头部 -->
      <div class="page-header">
        <el-button 
          link 
          @click="goBack" 
          class="back-btn"
        >
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
        <h2>我的订单</h2>
      </div>

      <!-- 状态筛选标签栏 -->
      <div class="status-tabs">
        <div class="tabs-container">
          <div 
            v-for="tab in statusTabs" 
            :key="tab.key"
            :class="['tab-item', { active: activeTab === tab.key }]"
            @click="handleTabChange(tab.key)"
          >
            <span class="tab-label">{{ tab.label }}</span>
            <el-badge 
              v-if="tab.count > 0" 
              :value="tab.count" 
              :hidden="false"
              class="tab-badge"
            />
          </div>
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-icon class="is-loading" size="40"><Loading /></el-icon>
        <p>加载中...</p>
      </div>

      <!-- 空状态 -->
      <div v-else-if="orders.length === 0" class="empty-container">
        <el-empty description="暂无订单" />
      </div>

      <!-- 订单列表 -->
      <div v-else class="orders-list">
        <div 
          v-for="order in orders" 
          :key="order.id" 
          class="order-card"
        >
          <div class="order-header">
            <div class="store-info">
              <div class="store-avatar">
                <img 
                  v-if="order.storeImage" 
                  :src="order.storeImage" 
                  :alt="order.storeName"
                  class="store-image"
                  @error="handleImageError"
                />
                <el-icon v-else class="store-icon"><Shop /></el-icon>
              </div>
              <span class="store-name">{{ order.storeName }}</span>
            </div>
            <div class="order-meta">
              <span class="order-time">{{ formatTime(order.createTime) }}</span>
              <span 
                class="order-status" 
                :style="{ color: getOrderStatusColor(order.status) }"
              >
                {{ getOrderStatusText(order.status) }}
              </span>
            </div>
          </div>
          
          <div class="order-content">
            <div class="order-items">
              <!-- 如果有商品详情，显示商品列表 -->
              <div 
                v-if="order.items && order.items.length > 0"
                v-for="item in order.items" 
                :key="item.id"
                class="order-item"
              >
                <img :src="item.foodImage || '/placeholder-food.png'" :alt="item.foodName" class="item-image" />
                <div class="item-info">
                  <h4>{{ item.foodName }}</h4>
                  <p class="item-specs" v-if="item.attributes && item.attributes.length">
                    {{ item.attributes.map(attr => `${attr.name}: ${attr.options.join(', ')}`).join('; ') }}
                  </p>
                  <p class="item-price">¥{{ item.price }} × {{ item.quantity }}</p>
                </div>
                <div class="item-total">
                  ¥{{ (item.subtotal || item.amount || (item.price * item.quantity)).toFixed(2) }}
                </div>
              </div>
              
            
            </div>
            
            <!-- 订单备注 -->
            <div v-if="order.remark" class="order-remark">
              <span class="remark-label">备注：</span>
              <span class="remark-text">{{ order.remark }}</span>
            </div>
          </div>
          
          <div class="order-footer">
            <div class="order-summary">
              <div class="order-total">
                <!-- <span>共{{ getOrderItemCount(order) }}件商品</span> -->
                <div class="price-breakdown">
                  <div class="price-item">
                    <span>商品金额：</span>
                    <span>¥{{ order.goodsAmount || order.totalAmount }}</span>
                  </div>
                  <div class="price-item" v-if="order.deliveryFee">
                    <span>配送费：</span>
                    <span>¥{{ order.deliveryFee }}</span>
                  </div>
                  <div class="price-item" v-if="order.packageFee">
                    <span>包装费：</span>
                    <span>¥{{ order.packageFee }}</span>
                  </div>
                  <div class="price-total">
                    <span>实付：</span>
                    <strong>¥{{ order.totalAmount }}</strong>
                  </div>
                </div>
              </div>
            </div>
            <div class="order-actions">
              <el-button 
                v-for="action in getOrderActions(order)" 
                :key="action.text"
                :type="action.type as any"
                size="small"
                @click="action.action"
              >
                {{ action.text }}
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="total > pageSize" class="pagination-container">
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          layout="prev, pager, next"
          @current-change="handlePageChange"
        />
      </div>
    </div>

    <!-- 支付对话框 -->
    <PaymentDialog
      v-if="currentOrder"
      :visible="paymentVisible"
      :order-info="currentOrder"
      :store-name="currentOrder.storeName"
      :paying="paying"
      @update:visible="paymentVisible = $event"
      @pay="handlePaymentSuccess"
      @cancel="handlePaymentCancel"
      @close="handlePaymentCancel"
    />
  </CustomerLayout>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  ArrowLeft, 
  Loading,
  Shop,
  Picture,
  Van,
  Refresh
} from '@element-plus/icons-vue';
import CustomerLayout from "@/components/customer/CustomerLayout.vue";
import PaymentDialog from "@/components/customer/PaymentDialog.vue";
import { orderApi } from '@/api/customer';
import type { Order } from '@/types/customer';
import { formatImageUrl } from '@/utils/image';

const router = useRouter();
const route = useRoute();

// 响应式数据
const loading = ref(true);
const paying = ref(false);
const paymentVisible = ref(false);
const activeTab = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

const orders = ref<Order[]>([]);
const currentOrder = ref<Order | null>(null);

// 订单详情加载队列管理
const loadingQueue = ref<Order[]>([]);
const isLoadingDetails = ref(false);

// 状态筛选标签配置
const statusTabs = ref([
  { key: '', label: '全部', count: 0 },
  { key: 'ORDER_CREATED', label: '待支付', count: 0 },
  { key: 'PENDING', label: '待确认', count: 0 },
  { key: 'DELIVERING', label: '配送中', count: 0 }, // 修改为业务状态组合
  { key: 'COMPLETED', label: '已完成', count: 0 }, // 修改为COMPLETED
  { key: 'CANCELLED', label: '已取消', count: 0 },
]);

// 从路由参数初始化状态
const initFromRoute = () => {
  const routeTab = route.query.tab as string;
  if (routeTab && statusTabs.value.some(tab => tab.key === routeTab)) {
    activeTab.value = routeTab;
  }
  
  const routePage = parseInt(route.query.page as string);
  if (routePage && routePage > 0) {
    currentPage.value = routePage;
  }
};

// 监听路由变化
watch(() => route.query, (newQuery) => {
  if (route.name === 'CustomerOrders') {
    initFromRoute();
    fetchOrders();
  }
});

// 更新浏览器URL
const updateRouteQuery = () => {
  router.replace({
    query: {
      ...route.query,
      tab: activeTab.value || undefined,
      page: currentPage.value > 1 ? currentPage.value.toString() : undefined
    }
  });
};

// 返回上一页
const goBack = () => {
  router.back();
};

// 处理标签切换
const handleTabChange = (tabKey: string) => {
  activeTab.value = tabKey;
  currentPage.value = 1;
  updateRouteQuery();
  fetchOrders();
};

// 处理订单数据，转换API响应格式到组件期望格式
const processOrderData = (apiData: any[]): Order[] => {
  // 确保输入是数组
  if (!Array.isArray(apiData)) {
    console.error('processOrderData: 输入不是数组', typeof apiData, apiData);
    return [];
  }
  
  // 并行处理订单，但不等待所有详情加载完成，先返回基础信息
  const processedOrders = apiData.map((item) => {
    console.log('处理单个订单项:', item);
    
    const baseOrder: Order = {
      id: item.id,
      orderNo: item.orderNo || `ORDER-${item.id}`,
      userId: item.userId || 0,
      storeId: item.storeId || 0,
      storeName: item.storeName || '未知商家',
      storeImage: item.storeImage || '',
      totalAmount: item.totalAmount || 0,
      status: item.status,
      items: [], // 初始为空，后续异步加载
      address: {
        id: 0,
        name: '',
        phone: '',
        province: '',
        city: '',
        district: '',
        detail: item.deliveryAddress || '',
        isDefault: false
      },
      createTime: item.createdAt || item.createTime || '',
      remark: item.remark || '',
      deliveryFee: item.deliveryFee || 0,
      packageFee: item.packageFee || 0,
      paymentAmount: item.paymentAmount || item.totalAmount || 0
    };
    
    return baseOrder;
  });
  
  // 使用队列方式串行加载订单详情，避免并发请求过多
  batchLoadOrderDetails(processedOrders);
  
  return processedOrders;
};

// 批量加载订单详情（限制并发数）
const maxConcurrent = 2; // 降低并发数到2个
const requestDelay = 500; // 增加请求间隔到500ms

const batchLoadOrderDetails = async (ordersToLoad: Order[]) => {
  // 将订单加入队列
  loadingQueue.value.push(...ordersToLoad);
  
  // 如果已经在加载中，直接返回
  if (isLoadingDetails.value) {
    return;
  }
  
  isLoadingDetails.value = true;
  
  try {
    console.log(`开始批量加载 ${loadingQueue.value.length} 个订单详情，并发数: ${maxConcurrent}`);
    
    // 分批处理，每批最多处理maxConcurrent个订单
    while (loadingQueue.value.length > 0) {
      const batch = loadingQueue.value.splice(0, maxConcurrent);
      console.log(`处理批次: ${batch.map(o => o.id).join(', ')}`);
      
      // 并发处理当前批次
      const promises = batch.map((order, index) => 
        // 为每个请求添加不同的延迟，进一步分散请求时间
        new Promise(resolve => {
          setTimeout(() => {
            loadOrderDetails(order)
              .then(() => resolve(null))
              .catch(error => {
                console.warn(`订单 ${order.id} 详情加载失败:`, error.message);
                resolve(null);
              });
          }, index * 100); // 每个请求间隔100ms
        })
      );
      
      // 等待当前批次完成
      await Promise.allSettled(promises);
      
      // 批次之间增加延迟，避免服务器压力过大
      if (loadingQueue.value.length > 0) {
        console.log(`批次完成，等待 ${requestDelay}ms 后处理下一批...`);
        await new Promise(resolve => setTimeout(resolve, requestDelay));
      }
    }
    
    console.log('所有订单详情加载完成');
  } finally {
    isLoadingDetails.value = false;
  }
};

// 异步加载订单详情
const loadOrderDetails = async (order: Order, retryCount = 0): Promise<void> => {
  const maxRetries = 3; // 增加重试次数到3次
  
  try {
    console.log(`[订单${order.id}] 开始加载详情... (尝试 ${retryCount + 1}/${maxRetries + 1})`);
    
    // 为每个请求添加随机延迟，避免同时发送
    const randomDelay = Math.random() * 200;
    await new Promise(resolve => setTimeout(resolve, randomDelay));
    
    const orderDetailResponse = await orderApi.getOrderDetail(order.id);
    console.log(`[订单${order.id}] API响应状态:`, orderDetailResponse.status);
    
    if (orderDetailResponse.status === 200 && orderDetailResponse.data) {
      const orderDetail = orderDetailResponse.data;
      console.log(`[订单${order.id}] 详情加载成功`);
      
      // 处理商品数据，转换API格式到组件期望格式
      const processedItems = (orderDetail.items || []).map((item: any) => ({
        id: item.id,
        foodId: item.foodId,
        foodName: item.foodName,
        foodImage: item.foodImage || '',
        price: item.price || 0,
        quantity: item.quantity || 1,
        subtotal: item.amount || (item.price * item.quantity) || 0,
        amount: item.amount || (item.price * item.quantity) || 0, // 保留原始amount字段
        attributes: [] // API暂时没有返回属性信息，设为空数组
      }));
      
      // 找到对应的订单并更新其信息
      const orderIndex = orders.value.findIndex(o => o.id === order.id);
      
      if (orderIndex !== -1) {
        // 更新商品信息
        orders.value[orderIndex].items = processedItems;
        
        // 更新地址信息（如果API返回了详细地址）
        if (orderDetail.deliveryAddress) {
          const addr = orderDetail.deliveryAddress;
          orders.value[orderIndex].address = {
            id: addr.id || 0,
            name: addr.receiver || '',
            phone: addr.phone || '',
            province: addr.province || '',
            city: addr.city || '',
            district: addr.district || '',
            detail: addr.detailAddress || '',
            isDefault: addr.isDefault === 1
          };
        }
        
        // 更新其他可能的字段
        if (orderDetail.remark) {
          orders.value[orderIndex].remark = orderDetail.remark;
        }
        if (orderDetail.deliveryFee !== undefined) {
          orders.value[orderIndex].deliveryFee = orderDetail.deliveryFee;
        }
        if (orderDetail.paymentAmount !== undefined) {
          orders.value[orderIndex].paymentAmount = orderDetail.paymentAmount;
        }
        
        console.log(`[订单${order.id}] 详情更新完成`);
      } else {
        console.warn(`[订单${order.id}] 未找到对应订单在当前列表中`);
      }
    } else {
      throw new Error(`API响应状态异常: ${orderDetailResponse.status}`);
    }
  } catch (error: any) {
    console.error(`[订单${order.id}] 详情加载失败:`, error.message || error);
    
    // 判断是否应该重试
    const shouldRetry = retryCount < maxRetries && (
      error.name === 'NetworkError' || 
      error.code === 'ECONNABORTED' || 
      error.code === 'NETWORK_ERROR' ||
      (error.response && error.response.status >= 500) ||
      error.message?.includes('timeout') ||
      error.message?.includes('网络连接失败')
    );
    
    if (shouldRetry) {
      const retryDelay = Math.min(1000 * Math.pow(2, retryCount), 5000); // 最大延迟5秒
      console.log(`[订单${order.id}] 将在 ${retryDelay}ms 后重试 (${retryCount + 1}/${maxRetries})`);
      
      // 指数退避延迟重试，但加上随机因子避免惊群效应
      const jitteredDelay = retryDelay + Math.random() * 1000;
      await new Promise(resolve => setTimeout(resolve, jitteredDelay));
      
      return loadOrderDetails(order, retryCount + 1);
    }
    
    // 重试次数用完或不符合重试条件
    console.warn(`[订单${order.id}] 详情加载最终失败，显示基础信息 (错误: ${error.message})`);
  }
};

// 处理分页
const handlePageChange = (page: number) => {
  currentPage.value = page;
  updateRouteQuery();
  fetchOrders();
};

// 获取订单状态文本
const getOrderStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'ORDER_CREATED': '待支付',
    'PENDING': '待确认',
    'MERCHANT_CONFIRMED': '已确认',
    'READY_WAITING_RIDER': '等待配送',
    'ACCEPTED': '配送中',        // 添加ACCEPTED状态映射
    'RIDER_ASSIGNED': '配送中',
    'FOOD_PICKED': '配送中',
    'DELIVERED': '已送达',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  };
  return statusMap[status] || '未知状态';
};

// 获取订单状态颜色
const getOrderStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    'ORDER_CREATED': '#dc2626',      // 红色 - 待支付
    'PENDING': '#f59e0b',            // 琥珀色 - 待确认
    'MERCHANT_CONFIRMED': '#d97706', // 橙色 - 已确认
    'READY_WAITING_RIDER': '#ea580c', // 橙红色 - 等待配送
    'ACCEPTED': '#0891b2',           // 青色 - 配送中（兼容旧数据）
    'RIDER_ASSIGNED': '#0891b2',     // 青色 - 配送中
    'FOOD_PICKED': '#0891b2',        // 青色 - 配送中
    'DELIVERED': '#0891b2',          // 青色 - 已送达（配送中状态）
    'COMPLETED': '#059669',          // 翠绿色 - 已完成
    'CANCELLED': '#6b7280'           // 灰色 - 已取消
  };
  return colorMap[status] || '#6b7280';
};

// 查看订单详情
const viewOrderDetail = (orderId: number) => {
  router.push(`/customer/order/${orderId}`);
};

// 支付订单
const payOrder = (order: Order) => {
  currentOrder.value = order;
  paymentVisible.value = true;
};

// 处理支付成功
const handlePaymentSuccess = async () => {
  paymentVisible.value = false;
  ElMessage.success('支付成功');
  await fetchOrders();
  await fetchOrderCounts();
};

// 处理支付取消
const handlePaymentCancel = () => {
  paymentVisible.value = false;
};

// 取消订单
const cancelOrder = async (order: Order) => {
  try {
    await ElMessageBox.confirm(
      '确定要取消这个订单吗？取消后无法恢复。',
      '取消订单',
      {
        confirmButtonText: '确定取消',
        cancelButtonText: '我再想想',
        type: 'warning',
      }
    );

    await orderApi.cancelOrder(order.id);
    ElMessage.success('订单已取消');
    await fetchOrders();
    await fetchOrderCounts();
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '取消订单失败');
    }
  }
};

// 确认收货
const confirmOrder = async (order: Order) => {
  try {
    await ElMessageBox.confirm(
      '确认收到商品了吗？确认后订单将完成。',
      '确认收货',
      {
        confirmButtonText: '确认收货',
        cancelButtonText: '再等等',
        type: 'info',
      }
    );

    await orderApi.confirmOrder(order.id);
    ElMessage.success('已确认收货');
    await fetchOrders();
    await fetchOrderCounts();
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '确认收货失败');
    }
  }
};

// 催单
const urgeOrder = async (order: Order) => {
  try {
    await orderApi.urgeOrder(order.id);
    ElMessage.success('催单成功，商家会尽快处理');
  } catch (error: any) {
    ElMessage.error(error.message || '催单失败');
  }
};

// 获取订单列表
const fetchOrders = async () => {
  try {
    loading.value = true;
    
    // 处理配送中状态组合
    let statusParam = activeTab.value || undefined;
    if (activeTab.value === 'DELIVERING') {
      // 配送中包含多个状态，需要特殊处理
      statusParam = undefined; // 获取全部订单，然后前端过滤
    }
    
    const response = await orderApi.getOrders({
      status: statusParam,
      page: currentPage.value,
      size: pageSize.value
    });
    
    console.log('订单API响应:', response);
    
    if (response.status === 200) {
      const responseData = response.data;
      let rawOrders: any[] = [];
      
      console.log('原始API响应数据:', responseData);
      
      // 处理可能的分页数据格式
      if (responseData?.data?.content && Array.isArray(responseData.data.content)) {
        // 嵌套的分页格式 {data: {content: [], totalElements: 23}}
        rawOrders = responseData.data.content;
        total.value = responseData.data.totalElements || 0;
      } else if (responseData?.content && Array.isArray(responseData.content)) {
        // 直接分页格式 {content: [], totalElements: 23}
        rawOrders = responseData.content;
        total.value = responseData.totalElements || 0;
      } else if (Array.isArray(responseData)) {
        // 直接数组格式
        rawOrders = responseData;
        total.value = responseData.length;
      } else if (responseData?.data && Array.isArray(responseData.data)) {
        // 其他格式
        rawOrders = responseData.data;
        total.value = responseData.total || responseData.data.length;
      } else {
        // 如果都不是，设为空数组
        console.warn('无法解析API响应数据结构:', responseData);
        rawOrders = [];
        total.value = 0;
      }
      
      console.log('rawOrders 类型:', typeof rawOrders, 'rawOrders:', rawOrders);
      
      // 确保 rawOrders 是数组
      if (!Array.isArray(rawOrders)) {
        console.warn('rawOrders 不是数组，转换为空数组');
        rawOrders = [];
      }
      
      // 转换API数据格式到组件期望格式
      // 处理订单数据
      let processedOrders = processOrderData(rawOrders);
      
      // 如果是配送中状态，进行前端过滤
      if (activeTab.value === 'DELIVERING') {
        const deliveringStatuses = ['MERCHANT_CONFIRMED', 'READY_WAITING_RIDER', 'ACCEPTED', 'RIDER_ASSIGNED', 'FOOD_PICKED', 'DELIVERED'];
        processedOrders = processedOrders.filter(order => 
          deliveringStatuses.includes(order.status)
        );
        total.value = processedOrders.length;
      }
      
      orders.value = processedOrders;
      
      console.log('处理后的订单数据:', orders.value);
    } else {
      throw new Error(response.data?.message || '获取订单列表失败');
    }
    
  } catch (error: any) {
    console.error('获取订单列表失败:', error);
    ElMessage.error(error.message || '获取订单列表失败');
    orders.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 获取各状态订单数量
const fetchOrderCounts = async () => {
  try {
    const statusList = ['ORDER_CREATED', 'PENDING', 'COMPLETED', 'CANCELLED'];
    const deliveringStatuses = ['MERCHANT_CONFIRMED', 'READY_WAITING_RIDER', 'RIDER_ASSIGNED', 'FOOD_PICKED', 'DELIVERED'];
    const counts: Record<string, number> = {};
    let totalCount = 0;
    
    // 获取单一状态的订单数量
    for (const status of statusList) {
      try {
        const response = await orderApi.getOrders({ page: 1, size: 1, status });
        
        let count = 0;
        if (response.status === 200) {
          const responseData = response.data;
          if (responseData?.totalElements) {
            count = responseData.totalElements;
          } else if (responseData?.total) {
            count = responseData.total;
          } else if (Array.isArray(responseData)) {
            count = responseData.length;
          }
        }
        
        counts[status] = count;
        totalCount += count;
      } catch (error) {
        console.error(`获取${status}状态订单数量失败:`, error);
        counts[status] = 0;
      }
    }
    
    // 单独计算配送中状态的总数量
    let deliveringCount = 0;
    for (const status of deliveringStatuses) {
      try {
        const response = await orderApi.getOrders({ page: 1, size: 1, status });
        
        let count = 0;
        if (response.status === 200) {
          const responseData = response.data;
          if (responseData?.totalElements) {
            count = responseData.totalElements;
          } else if (responseData?.total) {
            count = responseData.total;
          } else if (Array.isArray(responseData)) {
            count = responseData.length;
          }
        }
        
        deliveringCount += count;
      } catch (error) {
        console.error(`获取${status}状态订单数量失败:`, error);
      }
    }
    
    // 更新标签计数
    statusTabs.value.forEach(tab => {
      if (tab.key === '') {
        tab.count = totalCount + deliveringCount;
      } else if (tab.key === 'DELIVERING') {
        tab.count = deliveringCount;
      } else {
        tab.count = counts[tab.key] || 0;
      }
    });
    
  } catch (error) {
    console.error('获取订单统计失败:', error);
  }
};

// 格式化时间
const formatTime = (timeStr: string) => {
  const date = new Date(timeStr);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));
  
  if (days === 0) {
    const hours = Math.floor(diff / (1000 * 60 * 60));
    if (hours === 0) {
      const minutes = Math.floor(diff / (1000 * 60));
      return minutes <= 1 ? '刚刚' : `${minutes}分钟前`;
    }
    return `${hours}小时前`;
  } else if (days === 1) {
    return '昨天';
  } else if (days < 7) {
    return `${days}天前`;
  } else {
    return date.toLocaleDateString();
  }
};

// 处理图片加载错误
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement;
  img.style.display = 'none';
  // 显示默认图标
  const parent = img.parentElement;
  if (parent) {
    const icon = parent.querySelector('.store-icon');
    if (icon) {
      (icon as HTMLElement).style.display = 'block';
    }
  }
};

// 获取订单商品总数量
const getOrderItemCount = (order: Order) => {
  if (!order.items || order.items.length === 0) {
    return 0;
  }
  return order.items.reduce((total, item) => total + item.quantity, 0);
};

// 获取订单操作按钮
const getOrderActions = (order: Order) => {
  const actions: Array<{ text: string; type: string; action: () => void | Promise<void> }> = [];
  
  switch (order.status) {
    case 'ORDER_CREATED':
      actions.push({ text: '去支付', type: 'primary', action: () => payOrder(order) });
      actions.push({ text: '取消订单', type: 'default', action: () => cancelOrder(order) });
      break;
    case 'PENDING':
    case 'MERCHANT_CONFIRMED':
    case 'READY_WAITING_RIDER':
      actions.push({ text: '催单', type: 'default', action: () => urgeOrder(order) });
      break;
    case 'RIDER_ASSIGNED':
    case 'FOOD_PICKED':
      actions.push({ text: '催单', type: 'default', action: () => urgeOrder(order) });
      break;
    case 'DELIVERED':
      actions.push({ text: '确认收货', type: 'primary', action: () => confirmOrder(order) });
      break;
    case 'COMPLETED':
      // 检查是否已评价（这个字段需要后端提供）
      const hasReviewed = (order as any).reviewed || false;
      if (!hasReviewed) {
        actions.push({ text: '评价', type: 'primary', action: async () => { 
          await router.push(`/customer/order/${order.id}/review`);
        }});
      }
      break;
  }
  
  actions.push({ text: '查看详情', type: 'default', action: () => viewOrderDetail(order.id) });
  return actions;
};

// 手动重试加载单个订单详情
const retryLoadOrderDetail = async (orderId: number) => {
  try {
    // 找到订单在当前显示列表中的位置
    const orderIndex = orders.value.findIndex(o => o.id === orderId);
    if (orderIndex === -1) return;

    console.log(`[订单${orderId}] 手动重试加载详情...`);

    const orderDetailResponse = await orderApi.getOrderDetail(orderId);
    
    if (orderDetailResponse.status === 200 && orderDetailResponse.data) {
      const orderDetail = orderDetailResponse.data;
      console.log(`[订单${orderId}] 手动重试详情加载成功`);
      
      // 处理商品数据，转换API格式到组件期望格式
      const processedItems = (orderDetail.items || []).map((item: any) => ({
        id: item.id,
        foodId: item.foodId,
        foodName: item.foodName,
        foodImage: item.foodImage || '',
        price: item.price || 0,
        quantity: item.quantity || 1,
        subtotal: item.amount || (item.price * item.quantity) || 0,
        amount: item.amount || (item.price * item.quantity) || 0,
        attributes: []
      }));
      
      // 更新订单信息
      orders.value[orderIndex].items = processedItems;
      
      // 更新地址信息
      if (orderDetail.deliveryAddress) {
        const addr = orderDetail.deliveryAddress;
        orders.value[orderIndex].address = {
          id: addr.id || 0,
          name: addr.receiver || '',
          phone: addr.phone || '',
          province: addr.province || '',
          city: addr.city || '',
          district: addr.district || '',
          detail: addr.detailAddress || '',
          isDefault: addr.isDefault === 1
        };
      }
      
      // 更新其他字段
      if (orderDetail.remark) {
        orders.value[orderIndex].remark = orderDetail.remark;
      }
      if (orderDetail.deliveryFee !== undefined) {
        orders.value[orderIndex].deliveryFee = orderDetail.deliveryFee;
      }
      if (orderDetail.paymentAmount !== undefined) {
        orders.value[orderIndex].paymentAmount = orderDetail.paymentAmount;
      }
      
      ElMessage.success('订单详情重新加载成功');
    } else {
      ElMessage.error('获取订单详情失败');
    }
  } catch (error: any) {
    console.error(`[订单${orderId}] 手动重试加载失败:`, error);
    ElMessage.error('网络连接失败，请检查网络后重试');
  }
};

// 页面初始化
onMounted(() => {
  const initializeData = async () => {
    try {
      initFromRoute();
      await fetchOrders();
      await fetchOrderCounts();
    } catch (error) {
      console.error('页面初始化失败:', error);
    }
  };
  
  initializeData();
});
</script>

<style scoped>
.orders-container {
  max-width: 95%;
  margin: 0 auto;
  padding: 24px;
  background: linear-gradient(135deg, #fefcbf 0%, #fef3c7 100%);
  min-height: calc(100vh - 60px);
  transition: background 0.3s ease;
  min-width: 320px;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 32px;
  padding: 20px 24px;
  background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%);
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(245, 158, 11, 0.3);
  border: 1px solid rgba(217, 119, 6, 0.4);
  transition: background 0.3s ease, box-shadow 0.3s ease, border-color 0.3s ease;
}

.back-btn {
  margin-right: 16px;
  background: rgba(245, 158, 11, 0.2);
  color: #92400e;
  border: 1px solid rgba(146, 64, 14, 0.3);
  border-radius: 12px;
  padding: 10px;
  transition: all 0.3s ease;
}

.back-btn:hover {
  background: rgba(245, 158, 11, 0.3);
  transform: translateX(-2px);
}

.page-header h2 {
  margin: 0;
  font-size: 28px;
  color: #ffffff;
  font-weight: 700;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  letter-spacing: -0.025em;
  transition: color 0.3s ease;
}

.status-tabs {
  margin-bottom: 24px;
  background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(251, 191, 36, 0.2);
  border: 1px solid rgba(217, 119, 6, 0.3);
  overflow: hidden;
}

.tabs-container {
  display: flex;
  overflow-x: auto;
}

.tab-item {
  flex: 1;
  min-width: 100px;
  padding: 18px 24px;
  text-align: center;
  cursor: pointer;
  position: relative;
  border-bottom: 3px solid transparent;
  transition: all 0.3s ease;
  background: transparent;
  color: #92400e;
}

.tab-item:hover {
  background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%);
  color: #ffffff;
  transform: translateY(-1px);
}

.tab-item.active {
  color: #ffffff;
  border-bottom-color: #d78e39;
  background: linear-gradient(135deg, #f59e0b 0%, #d18f44 100%);
  font-weight: 600;
}

.tab-item.active::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(90deg, #fbbf24, #f59e0b);
}

.tab-label {
  font-size: 14px;
  font-weight: 600;
  letter-spacing: 0.025em;
}

.tab-badge {
  margin-left: 8px;
}

.tab-badge .el-badge__content {
  background: linear-gradient(135deg, #dc2626 0%, #b91c1c 100%);
  border: 2px solid #ffffff;
  box-shadow: 0 2px 8px rgba(220, 38, 38, 0.3);
}

.loading-container {
  text-align: center;
  padding: 50px 0;
  color: #999;
}

.empty-container {
  padding: 50px 0;
}

.orders-list {
  margin: 0;
}

.order-card {
  background: linear-gradient(135deg, #fffef7 0%, #fefce8 100%);
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(254, 240, 138, 0.15);
  margin-bottom: 20px;
  overflow: hidden;
  border: 1px solid rgba(254, 215, 79, 0.2);
  transition: all 0.3s ease;
  position: relative;
}

.order-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 30px rgba(254, 240, 138, 0.2);
  border-color: rgba(254, 215, 79, 0.3);
}

.order-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #fbbf24, #facc15, #eab308);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 20px 24px 16px;
  background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
  border-bottom: 1px solid rgba(254, 215, 79, 0.3);
  position: relative;
}

.store-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.store-avatar {
  position: relative;
  width: 40px;
  height: 40px;
  border-radius: 10px;
  overflow: hidden;
  background: rgba(254, 215, 79, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
}

.store-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 10px;
  border: 2px solid rgba(255, 255, 255, 0.3);
}

.store-icon {
  font-size: 20px;
  color: #d97706;
  display: none;
}

.store-avatar:has(.store-image:not([style*="display: none"])) .store-icon {
  display: none;
}

.store-avatar:not(:has(.store-image)) .store-icon,
.store-avatar:has(.store-image[style*="display: none"]) .store-icon {
  display: block;
}

.store-name {
  font-weight: 600;
  color: #92400e;
  font-size: 16px;
  letter-spacing: -0.025em;
  text-shadow: none;
}

.order-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 6px;
}

.order-time {
  font-size: 12px;
  color: #92400e;
  background: rgba(254, 215, 79, 0.3);
  padding: 4px 8px;
  border-radius: 6px;
  font-weight: 500;
}

.order-status {
  font-weight: 600;
  font-size: 14px;
  padding: 6px 12px;
  border-radius: 20px;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(4px);
  border: 1px solid currentColor;
  text-transform: uppercase;
  letter-spacing: 0.025em;
  color: #92400e;
}

.order-content {
  padding: 20px 24px;
  background: linear-gradient(135deg, #fffbeb 0%, #fefce8 100%);
}

.order-items {
  margin: 0;
}

.order-item {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 16px;
  padding: 16px;
  border-radius: 12px;
  background: linear-gradient(135deg, #fffbeb 0%, #fef9c3 100%);
  border: 1px solid rgba(217, 119, 6, 0.15);
  transition: all 0.2s ease;
}

.order-item:hover {
  background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
  border-color: rgba(245, 158, 11, 0.25);
  transform: translateX(4px);
}

.order-item:last-child {
  margin-bottom: 0;
}

.order-item-placeholder {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
  border-radius: 12px;
  background: linear-gradient(135deg, #fef9c3 0%, #fef3c7 100%);
  border: 2px dashed rgba(217, 119, 6, 0.3);
  color: #a16207;
}

.placeholder-icon {
  font-size: 32px;
  color: #d97706;
  opacity: 0.7;
}

.placeholder-text p {
  margin: 0;
  font-weight: 500;
}

.placeholder-note {
  font-size: 12px;
  opacity: 0.8;
  margin-top: 4px !important;
}

.item-image {
  width: 70px;
  height: 70px;
  border-radius: 12px;
  object-fit: cover;
  flex-shrink: 0;
  box-shadow: 0 4px 12px rgba(217, 119, 6, 0.2);
  border: 2px solid rgba(251, 191, 36, 0.5);
}

.item-info {
  flex: 1;
  min-width: 0;
}

.item-info h4 {
  margin: 0 0 6px 0;
  font-size: 15px;
  color: #d46621;
  line-height: 1.4;
  font-weight: 600;
  letter-spacing: -0.025em;
}

.item-specs {
  margin: 0 0 6px 0;
  font-size: 12px;
  color: #a16207;
  line-height: 1.3;
  background: rgba(161, 98, 7, 0.1);
  padding: 4px 8px;
  border-radius: 6px;
  display: inline-block;
}

.item-price {
  margin: 0;
  font-size: 13px;
  color: #78350f;
  font-weight: 500;
}

.item-total {
  font-size: 16px;
  font-weight: 700;
  color: #059669;
  background: rgba(5, 150, 105, 0.15);
  padding: 8px 12px;
  border-radius: 8px;
  flex-shrink: 0;
}

.order-remark {
  margin-top: 16px;
  padding: 16px;
  background: linear-gradient(135deg, #fffbeb 0%, #fbbf24 0.05%, #fffbeb 100%);
  border-radius: 12px;
  border-left: 4px solid #f59e0b;
  font-size: 13px;
}

.remark-label {
  color: #92400e;
  font-weight: 600;
}

.remark-text {
  color: #78350f;
  font-weight: 500;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  padding: 20px 24px;
  background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
  border-top: 1px solid rgba(217, 119, 6, 0.2);
}

.order-summary {
  flex: 1;
}

.order-total {
  font-size: 14px;
  color: #92400e;
  font-weight: 600;
}

.price-breakdown {
  margin-top: 12px;
  background: rgba(255, 255, 255, 0.8);
  padding: 12px;
  border-radius: 10px;
  backdrop-filter: blur(4px);
  border: 1px solid rgba(217, 119, 6, 0.2);
}

.price-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 6px;
  font-size: 13px;
  color: #a16207;
  font-weight: 500;
}

.price-item:last-child {
  margin-bottom: 0;
}

.price-total {
  display: flex;
  justify-content: space-between;
  margin-top: 12px;
  padding-top: 12px;
  border-top: 2px solid rgba(245, 158, 11, 0.3);
  font-size: 15px;
  color: #78350f;
  font-weight: 600;
}

.price-total strong {
  color: #dc2626;
  font-size: 18px;
  font-weight: 800;
  text-shadow: 0 1px 2px rgba(220, 38, 38, 0.2);
}

.order-actions {
  display: flex;
  gap: 12px;
  margin-left: 20px;
}

.order-actions .el-button {
  border-radius: 10px;
  font-weight: 600;
  letter-spacing: 0.025em;
  padding: 10px 16px;
  transition: all 0.2s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.order-actions .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.order-actions .el-button--primary {
  background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
  border: none;
  color: #ffffff;
}

.order-actions .el-button--primary:hover {
  background: linear-gradient(135deg, #d97706 0%, #b45309 100%);
}

.order-actions .el-button--default {
  background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%);
  border: 1px solid rgba(217, 119, 6, 0.3);
  color: #92400e;
}

.order-actions .el-button--default:hover {
  background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
  color: #ffffff;
}

.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

@media (max-width: 768px) {
  .orders-container {
    padding: 15px;
  }
  
  .page-header h2 {
    font-size: 20px;
  }
  
  .tab-item {
    padding: 12px 15px;
    font-size: 13px;
  }
  
  .order-header {
    padding: 12px 15px;
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .order-meta {
    align-items: flex-start;
    gap: 2px;
  }
  
  .order-content {
    padding: 12px 15px;
  }
  
  .order-item {
    gap: 10px;
  }
  
  .item-image {
    width: 50px;
    height: 50px;
  }
  
  .item-info h4 {
    font-size: 13px;
  }
  
  .item-specs, .item-price {
    font-size: 11px;
  }
  
  .order-footer {
    padding: 12px 15px;
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .order-summary {
    margin: 0;
  }
  
  .order-actions {
    justify-content: flex-end;
    margin-left: 0;
    flex-wrap: wrap;
  }
  
  .order-actions .el-button {
    min-width: 70px;
  }
}

/* 暗色主题支持 */
body.customer-dark-theme .orders-container {
  background: linear-gradient(135deg, #2d2d2d 0%, #3a3a3a 100%);
}

body.customer-dark-theme .page-header {
  background: linear-gradient(135deg, #4a4a4a 0%, #5a5a5a 100%);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.1);
}

body.customer-dark-theme .back-btn {
  background: rgba(255, 167, 38, 0.2);
  color: #ffa726;
  border: 1px solid rgba(255, 167, 38, 0.3);
}

body.customer-dark-theme .back-btn:hover {
  background: rgba(255, 167, 38, 0.3);
}

body.customer-dark-theme .page-header h2 {
  color: #f0f0f0;
}

body.customer-dark-theme .status-tabs {
  background: linear-gradient(135deg, #3a3a3a 0%, #4a4a4a 100%);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.1);
}

body.customer-dark-theme .tab-item {
  color: #c0c0c0;
}

body.customer-dark-theme .tab-item:hover {
  background: linear-gradient(135deg, #5a5a5a 0%, #6a6a6a 100%);
  color: #f0f0f0;
}

body.customer-dark-theme .tab-item.active {
  color: #ffa726;
  border-bottom-color: #ffa726;
  background: linear-gradient(135deg, #4a4a4a 0%, #5a5a5a 100%);
}

body.customer-dark-theme .tab-item.active::before {
  background: linear-gradient(90deg, #ffa726, #ffb74d);
}

body.customer-dark-theme .loading-container {
  color: #c0c0c0;
}

body.customer-dark-theme .order-card {
  background: linear-gradient(135deg, #1c1917 0%, #292524 100%);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(251, 191, 36, 0.2);
}

body.customer-dark-theme .order-card:hover {
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.4);
  border-color: rgba(251, 191, 36, 0.4);
}

body.customer-dark-theme .order-card::before {
  background: linear-gradient(90deg, #fbbf24, #facc15, #eab308);
}

body.customer-dark-theme .order-header {
  background: linear-gradient(135deg, #451a03 0%, #78350f 100%);
  border-bottom: 1px solid rgba(251, 191, 36, 0.2);
}

body.customer-dark-theme .store-icon {
  background: linear-gradient(135deg, #ffa726 0%, #ffb74d 100%);
}

body.customer-dark-theme .store-name {
  color: #f0f0f0;
}

body.customer-dark-theme .order-id {
  color: #c0c0c0;
}

body.customer-dark-theme .order-status {
  color: #ffa726;
}

body.customer-dark-theme .order-time {
  color: #aaa;
}

body.customer-dark-theme .order-content {
  background: linear-gradient(135deg, #3a3a3a 0%, #444444 100%);
}

body.customer-dark-theme .item-info h4 {
  color: #f0f0f0;
}

body.customer-dark-theme .item-specs {
  color: #c0c0c0;
}

body.customer-dark-theme .item-price {
  color: #ffa726;
}

body.customer-dark-theme .order-footer {
  background: rgba(255, 255, 255, 0.05);
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

body.customer-dark-theme .summary-text {
  color: #c0c0c0;
}

body.customer-dark-theme .summary-value {
  color: #ffa726;
}

body.customer-dark-theme .el-button {
  border-color: rgba(255, 255, 255, 0.1);
}

body.customer-dark-theme .el-button--primary {
  background: linear-gradient(135deg, #ffa726 0%, #ffb74d 100%);
  border-color: #ffa726;
  color: #2d2d2d;
}

body.customer-dark-theme .el-button--danger {
  background: linear-gradient(135deg, #f44336 0%, #e57373 100%);
  border-color: #f44336;
}

body.customer-dark-theme .el-empty {
  color: #c0c0c0;
}
</style>
